package com.example.readwrite.alg;

import com.google.common.base.Preconditions;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import java.util.Collection;
import java.util.Properties;

public class MyShardingAlgorithm implements StandardShardingAlgorithm<Comparable<?>> {

    private static final String SHARDING_COUNT_KEY = "sharding-count";
    private Properties props = new Properties();
    private int shardingCount;

    public MyShardingAlgorithm() {
    }

    @Override
    public void init() {
        this.shardingCount = this.getShardingCount();
    }

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Comparable<?>> preciseShardingValue) {
        String[] strings = collection.toArray(new String[0]);
        int idx = (int) (this.getLongValue(preciseShardingValue.getValue()) % (long)this.shardingCount);
        return strings[idx];
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Comparable<?>> rangeShardingValue) {
        return null;
    }

    private long getLongValue(Comparable<?> value) {
        return value instanceof Number ? ((Number)value).longValue() : Long.parseLong(value.toString());
    }

    private int getShardingCount() {
        Preconditions.checkArgument(this.props.containsKey(SHARDING_COUNT_KEY), "Sharding count cannot be null.");
        return Integer.parseInt(this.props.get(SHARDING_COUNT_KEY).toString());
    }

    @Override
    public String getType() {
        return "CLASS_BASED";
    }


    public void setProps(Properties props) {
        this.props = props;
    }

}
